package com.shumi.fun;

import org.apache.commons.lang.StringUtils;

import java.text.MessageFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class QuerySQL {

	final String REGEX11 = "(?i)(where\\s{0,}1\\s{0,}=\\s{0,}1\\s{0,})(and)?";
	final String REGEXARG = "(?<=\\{)(\\S+)(?=\\})";
	final Pattern PATTERN11 = Pattern.compile(REGEX11);
	final Pattern PATTERNARG = Pattern.compile(REGEXARG);
	
	
	/**
	 * 根据查询参数spellsql
	 * 
	 * @param querysql
	 * @param size
	 * @param start
	 * @param order
	 * @param desc
	 * @param args
	 * */
	public String loadTableSQL(String querysql,Integer size,Integer start,String order,String desc, Map<String, String> args) {	
		String pageformat=" order by {0} {1} limit {2} offset {3}";
		if( size==null|| size<1){
			size=50;
		}
		if( start==null){
			start=0;
		}
		if(StringUtils.isBlank(order)){
			order="makedate";
		}
		if(StringUtils.isBlank(desc)){
			desc="desc";
		}
		String fixsql=MessageFormat.format(pageformat, order,desc,size,start);
		String tmpsql=loadSimpleSQL(querysql,args)+fixsql;
		return tmpsql;
	}
	
	/**
	 * 高级搜索统配{}
	 * @param querysql
	 * @param args
	 * */
	public String loadSimpleSQL(String querysql, Map<String, String> args){
		StringBuilder sb=new StringBuilder(256);
		String[] arr=querysql.split("BB_");
		sb.append(arr[0]);
		for(int i=1;i<arr.length;i++){
			Matcher mt = PATTERNARG.matcher(arr[i]);// 此处为改动部分
			boolean flag=true;
			Set<String> tmpSet=new HashSet<>();
			while(mt.find()){
				String argname=mt.group();
				flag=flag && args.containsKey(argname);
				tmpSet.add(argname);			
			}
			if(flag){
				sb.append(" and ");
				for (String argname : tmpSet) {
					arr[i]=arr[i].replace("{"+argname+"}",  args.get(argname));
				}
				sb.append(arr[i]);
				continue;
			}
		}
		return replate11(sb.toString());
	}
	
	String replate11(String sqlstr) {
		Matcher m = PATTERN11.matcher(sqlstr);
		while (m.find()) {
			if (m.group().toLowerCase().endsWith("and")) {
				sqlstr = sqlstr.replaceAll(m.group(), "where ");
			}
			sqlstr = sqlstr.replaceAll(m.group(), " ");
		}
		return sqlstr;
	}
	
	public static void main(String[] args) {
		Map<String, String> argsmap=new HashMap<>();
		//argsmap.put("makedate1", "2017-04-23");
		//argsmap.put("makedate2", "2017-04-24");
		//argsmap.put("seq", "12");
		String querysql="select * from client_task WHERE 1=1 BB_makedate  between '{makedate1}' and '{makedate2}'  BB_seq in {seq} BB_M123 like {M123}";
		QuerySQL querySQL=new QuerySQL();
		String sql=querySQL.loadSimpleSQL(querysql, argsmap);
		System.out.println(sql);
		
	}

}
